package com.sharepics.services;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.googlecode.objectify.Key;
import com.sharepics.bean.Album;
import com.sharepics.bean.Picture;
import com.sharepics.dao.AlbumDAO;
import com.sharepics.dao.PictureDAO;

@Service
public class AlbumService {

	@Autowired
	private AlbumDAO albumDAO;
	@Autowired
	private PictureDAO pictureDAO;
	
	public Picture addPicture(Picture pic,Long albumId,String bytes64Encoded) throws IOException{
		
		Base64 base64 = new Base64();
		byte[] data = base64.decode(bytes64Encoded);
		BlobKey blobKey = putInBlobStore(pic.getContentType(),data);
		pic.setBlob(blobKey);
		pic.setAlbumId(albumId);
		Key<Picture> key = pictureDAO.save(pic);
		Album album = albumDAO.get(albumId);
		albumDAO.update(album);
		return pic;
	}
	
	 public static BlobKey putInBlobStore(String contentType, byte[] filebytes) throws IOException {

	        // Get a file service
	          FileService fileService = FileServiceFactory.getFileService();
	          AppEngineFile file = fileService.createNewBlobFile(contentType);

	          // Open a channel to write to it
	          boolean lock = true;
	          FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

	        
	          
	         
	          ByteBuffer bb = ByteBuffer.wrap(filebytes);
	          writeChannel.write(bb);

	          writeChannel.closeFinally();

	        return fileService.getBlobKey(file);
	    }

}
